﻿using D.B.Data.API.Applications.Command.MenusCommand;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;

namespace D.B.Data.API.Applications.CommandHandler.MenusCommandHandler
{
    public class UpdateMenusCommandHandler : IRequestHandler<UpdateMenusCommand, APIResult<int>>
    {
        private readonly IBaseRepository<MenusModel> baseRepository;

        public UpdateMenusCommandHandler(IBaseRepository<MenusModel> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        public Task<APIResult<int>> Handle(UpdateMenusCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var res = baseRepository.GetAll();
            //查询选择父级 里所有的子集 除了自己
            var list = res.Where(s => s.Pid == request.Pid && !s.IsDel&&s.Id!=request.Id).Select(s => s.MenuName);

            var Isname = list.Contains(request.MenuName);
            if (Isname)
            {
                result.Code = EnumCode.File;
                result.Msg = "菜单名称重复";
                return Task.FromResult(result);
            }

            var data = res.FirstOrDefault(s => s.Id == request.Id)!;
            data.Url= request.Url;
            data.MenuName= request.MenuName;
            data.Pid= request.Pid;
            data.UpDataTime = DateTime.Now;
            data.UpDataUserId= request.UserId;
            var count=baseRepository.Update(data);
            if(count > 0)
            {
                result.Code = EnumCode.Ok;
                result.Msg = "修改成功";
                
            }
            else
            {
                result.Code = EnumCode.File;
                result.Msg = "修改失败";
            }
            return Task.FromResult(result);
            
        }
    }
}
